import rclpy
import cv2
from pyzbar import pyzbar
from rclpy.node import Node
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
class QR_Identify(Node):
    def __init__(self,name) -> None:
        super().__init__(name)
        self.br = CvBridge()
        self.get_logger().info("功能启动!!!")
        self.identify_sub=self.create_subscription(Image,"camera/image_raw",self.command_callback,10)
        self.identify_pub=self.create_publisher(String,"QR_Code_Content",10)
    def command_callback(self,massage):
        frame = self.br.imgmsg_to_cv2(massage)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        barcodes = pyzbar.decode(gray) 
        acc=String()
        for barcode in barcodes:
            (x, y, w, h) = barcode.rect
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            barcodeData = barcode.data.decode("utf-8")
            barcodeType = barcode.type
            text = "{}".format(barcodeData)
            cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
            if barcodeType=="QRCODE":
                glass="二维码"
            elif barcodeType=="EAN13":
                glass="条形码"
            else :
                glass=barcodeType
            self.get_logger().info("二维码类别： {0} 内容： {1}".format(glass, barcodeData))
            acc.data=barcodeData
            self.identify_pub.publish(acc)


def main(args=None):
    rclpy.init(args=args)
    node=QR_Identify("qr")
    rclpy.spin(node)
    rclpy.shutown()


